/*
 *  Copyright (c) Iris Dev. team. All rights reserved.
 *  See http://www.communico.pro/license for details.
 *
 */
#include <ASDebugHelper.hpp>
#include <ASPool.hpp>
#include <ASLogCodes.hpp>
#include <ASLogger.hpp>

#include "ASMemcachedObject.hpp"
#include "ASMemcachedTest.hpp"

using namespace CAS;

namespace CAS_MOD
{

//
// A constructor
//
ASMemcachedTest::ASMemcachedTest()
{
	;;
}

//
// Handler
//
INT_32 ASMemcachedTest::Handler(CTPP::CDT   & oData,
                                ASRequest   & oRequest,
                                ASResponse  & oResponse,
                                ASPool      & oGlobalPool,
                                ASPool      & oVhostPool,
                                ASPool      & oRequestPool,
                                CTPP::CDT   & oLocationConfig,
                                ASObject    * pContextData,
                                CTPP::CDT   & oIMC,
                                ASLogger    & oLogger)
{
	using namespace CTPP;

	DEBUG_HELPER(&oLogger, "ASMemcachedTest::Handler");

	// Set HTTP header
	oResponse.SetHeader("X-Module", "ASMemcachedTest");

	// Get memcached object
	ASMemcachedObject * pMemcached = oGlobalPool.GetResourceByName<ASMemcachedObject>("MemdConnector");
	if (pMemcached == NULL)
	{
		DEBUG_HELPER_MESSAGE("Object `MemdConnector` NOT found in GLOBAL pool");
		oLogger.Warn("ASMemcachedTest: Memcached object `MemdConnector` NOT found in GLOBAL pool");

		pMemcached = oVhostPool.GetResourceByName<ASMemcachedObject>("MemdConnector");
		if (pMemcached == NULL)
		{
			DEBUG_HELPER_MESSAGE("Object `MemdConnector` NOT found in SERVER pool");
			oLogger.Warn("ASMemcachedTest: Memcached object `MemdConnector` NOT found in SERVER pool");
			return HANDLER_ERROR;
		}
	}

	// Data storage
	CDT oResult;

	static CCHAR_P sKeys[]   = { "somekey0", "somekey1", "somekey2", "somekey3", "somekey4", "somekey5"};
	static CCHAR_P sValues[] = { "someval0", "someval1", "someval2", "someval3", "someval4", "someval5"};
	for (UINT_32 iPos = 0; iPos < 6; ++iPos)
	{
		CCHAR_P szKey = sKeys[iPos];
		// Get data
		Memcached::eQueryResult oRC = pMemcached -> Get(szKey, oResult);
		if (oRC == Memcached::OK)
		{
			oData["memcached.get"][szKey] = oResult;
		}
		else if (oRC == Memcached::NOT_EXISTS)
		{
			pMemcached -> Set(szKey, sValues[iPos], 30);
			oData["memcached.set"][szKey] = sValues[iPos];
		}
		else
		{
			oLogger.Emerg("ASMemcachedTest: Can't get/set value from memcached. Code %d", (INT_32)oRC);
			return HANDLER_ERROR;
		}
	}

return HANDLER_OK;
}

//
// Get object type
//
CCHAR_P ASMemcachedTest::GetModuleType() const { return "ASHandler"; }

//
// Get module name
//
CCHAR_P ASMemcachedTest::GetObjectName() const { return "ASMemcachedTest"; }

//
// A destructor
//
ASMemcachedTest::~ASMemcachedTest() throw()
{
	;;
}

} // namespace CAS_MOD
// End.

